<!--
 * @Descripttion: 上传组件
 * @version: 
 * @Author: Bruce
 * @Date: 2020-11-10 16:38:57
 * @LastEditors: Bruce
 * @LastEditTime: 2020-11-11 15:27:02
-->


<template>
	<div>
		<el-upload :class="{uoloadSty:showBtnImg,disUoloadSty:noneBtnImg}" ref="uploadImg" action="#" :auto-upload="false" :multiple="false" :limit="1" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-change="changeHandler" :on-remove="removeHandler" :file-list="fileList" :disabled="disabled">
			<i class="el-icon-plus"></i>
			<div slot="tip" class="el-upload__tip">注:图片大小不超过{{size}}mb</div>
		</el-upload>

		<el-dialog :visible.sync="dialogVisible">
			<img width="100%" :src="dialogImageUrl" alt="" />
		</el-dialog>
	</div>
</template>

<script>
	import {
		getBase64
	} from "@/utils/getBase64.js"
	export default {
		props: {
			idPic: { //图片地址
				type: String,
			},
			disabled: { //是否禁用
				type: Boolean
			}
		},
		data() {
			return {
				dialogImageUrl: '',//弹窗图片
				dialogVisible: false,//弹窗显示
				showBtnImg: true,//显示添加按钮
				noneBtnImg: false,//隐藏添加按钮
				limitCountImg: 1, //上传图片的最大数量
				size: 1 ,//图片上传限制大小1mb
				fileList:[]//文件列表
			}
		},
		watch:{
			idPic:{
				handler(newVal){
					if(newVal){
						this.fileList = []
						this.fileList.push({url:newVal})
						this.noneBtnImg = this.fileList.length >= this.limitCountImg; //删除上传图片按钮
					}
				},
				immediate:true
			}
		},
		methods: {
			handlePictureCardPreview(file) { //放大图片
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},
			removeHandler(file, fileList) { //删除图片
				this.noneBtnImg = fileList.length >= this.limitCountImg; //添加上传图片按钮
				this.$emit("update:idPic","")//更新idPic
			},
			async changeHandler(file, fileList) { //添加图片
				this.noneBtnImg = fileList.length >= this.limitCountImg; //删除上传图片按钮
				
				const listSize = file.size / 1024 / 1024 < this.size //不超过1mb
				
				if (listSize) {
					const res = await getBase64(file.raw); //base64转码
					this.$emit("update:idPic", res)//更新idPic
				} else {
					this.$message.error(`上传图片大小超过限制`);
					fileList.splice(0,1)
					this.noneBtnImg = fileList.length >= this.limitCountImg; //添加上传图片按钮
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.disUoloadSty /deep/.el-upload--picture-card {
		display: none;
		/* 上传按钮隐藏 */
	}
</style>
